package com.woniu.util;

import io.jsonwebtoken.*;

import javax.crypto.spec.SecretKeySpec;
import javax.xml.bind.DatatypeConverter;
import java.security.Key;
import java.security.SignatureException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author 李桢
 * @date 2021/4/2 14:18
 */
public class JwtCreatUtils {

    /** 私钥密码，保存在服务器，客户端是不会直到密码的，以防止被攻击* */
    private static final String SECRET = "mysecret";

    /** 加密方式* */
    private static final SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;

    /**对私钥进行加密**/
    private static Key getkey() {
        byte[] apiKeySecretBytes = DatatypeConverter.parseBase64Binary(SECRET);
        return new SecretKeySpec(apiKeySecretBytes, signatureAlgorithm.getJcaName());
    }

    /**创建token**/
    public static String createToken(String username, int expireSeconds) {
        // 组合header :  {"alg": "HS256",  "typ": "JWT"}
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("alg", "HS256");
        map.put("typ", "JWT");
        JwtBuilder builder = Jwts.builder();
        builder.setHeaderParams(map);

        //有效荷载
        builder.claim("username", username);

        //生成第三部分
        builder.signWith(SignatureAlgorithm.HS256, getkey());
        //签发时间
        long nowMillis = System.currentTimeMillis();
        Date now = new Date(nowMillis);
        //设置过期时间
        if (expireSeconds >= 0) {
            long expMillis=nowMillis + (expireSeconds + 2) * 1000;
            Date expDate=new Date(expMillis);
            //过期时间
            builder.setExpiration(expDate);
        }
        builder.setIssuedAt(now);

        //构建jwt
        String token=builder.compact();
        return token;
    }

}
